import React, { Component } from 'react';
import BreadcrumbCustom from '../common/BreadcrumbCustom';
import { Card, Row, Col, Table, Icon, Popconfirm, Input, Button, message } from 'antd';
import './index.less';
import UserModal from './UserModal';
import Highlighter from 'react-highlight-words';
import AddModal from './addUser';
import fetchRequest from '../../fetch/fetchRequest';

//找到对应元素的索引
function catchIndex(arr, id) { //获取INDEX
    let index = 0;
    arr.forEach(function (ar, ind) {
        if (ar.id === id) {
            index = ind;
        }
    });
    return index;
}

export default class MIndex extends Component {
    state = {
        visible: false,
        formData: { username: '', password: '' },
        searchText: '',
    }

    // 获取用户列表
    getUsersList() {
        fetchRequest.fetchR('users', 'GET')
            .then((response) => {
                const data = response;
                // 获取admin用户的索引
                let adminIndex
                let admin_1Index
                for (var i = 0; i < data.length; i++) {
                    if (data[i].username === 'admin') {
                        adminIndex = i
                    }                    
                    if (data[i].username === 'admin_1') {
                        admin_1Index = i
                    }
                }
                // 剔除用户列表中的admin用户
                const newData = data.filter((item,index) => (index !== adminIndex && index !== admin_1Index))
                this.setState({
                    dataSource: newData
                })
            }).catch((err) => {  //网络请求失败返回的数据
                message.error('用户数据获取失败')
            });
    }

    // 通过用户名获得订单的id，以便做账单更新、删除
    getSettlement(username, method) {
        fetchRequest.fetchR(`settlement/${username}`, 'get')
            .then(res => {
                if (res.error === undefined) {
                    this.setState({
                        billId: res.id,
                        noSettlementBill: res.settlementDay
                    })

                    if (method === 'delete') {
                        // 删除对应用户的账单
                        fetchRequest.fetchR(`settlement/${res.id}`, 'delete').then(respones => { }).catch(err => { })
                    }
                }
            }).catch(err => {
                message.error('数据获取失败!');
            })
    }

    componentWillMount() {
        this.getUsersList()
    }

    // 接受新建表单数据（修改）
    saveFormRef = (form) => {
        this.form = form;
    };
    // 取消
    handleCancel = () => {
        this.setState({ visible: false });
    };
    // 用户修改点击
    editClick = (record) => {
        this.getSettlement(record.username, 'edit')

        const { dataSource } = this.state;
        const index = catchIndex(dataSource, record.id);
        this.setState({
            visible: true,
            tableRowKey: record.id,
            formData: dataSource[index]
        });
    };
    // 更新修改
    handleUpdate = () => {
        const form = this.form;
        const { tableRowKey, billId, noSettlementBill } = this.state;

        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            // 更新用户
            fetchRequest.fetchR(`users/${tableRowKey}`, 'put', values)
                .then(respones => {
                    this.getUsersList();
                    this.setState({
                        visible: false
                    });
                    message.success('更新成功！')
                    form.resetFields();
                }).catch(err => {
                    this.setState({
                        visible: false
                    });
                    message.error('更新失败!');
                    form.resetFields();
                })

            //更新用户账单中的对应用户名
            const settlement_body = {
                username: values.username,
                settlementDay: noSettlementBill
            };
            fetchRequest.fetchR(`settlement/${billId}`, 'put', settlement_body).then(res => { }).catch(err => { })
        });
    };

    // 用户删除
    deleteClick = (record) => {
        fetchRequest.fetchR(`users/${record.id}`, 'delete')
            .then(respones => {
                message.success('删除成功!');
                this.getUsersList();
            }).catch(err => {
                message.error('删除失败!');
            })

        this.getSettlement(record.username, 'delete')
    };

    // 用户名搜索
    getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({
            setSelectedKeys, selectedKeys, confirm, clearFilters,
        }) => (
                <div style={{ padding: 8 }}>
                    <Input
                        ref={node => { this.searchInput = node; }}
                        placeholder='搜索用户名'
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
                        style={{ width: 188, marginBottom: 8, display: 'block' }}
                    />
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm)}
                        icon="search"
                        size="small"
                        style={{ width: 90, marginRight: 8 }}
                    >
                        搜索
                        </Button>
                    <Button
                        onClick={() => this.handleReset(clearFilters)}
                        size="small"
                        style={{ width: 90 }}
                    >
                        重置
                        </Button>
                </div>
            ),
        filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
        onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
                setTimeout(() => this.searchInput.select());
            }
        },
        render: (text) => (
            <Highlighter
                highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
                searchWords={[this.state.searchText]}
                autoEscape
                textToHighlight={text.toString()}
            />
        ),
    });
    handleSearch = (selectedKeys, confirm) => {
        confirm();
        this.setState({ searchText: selectedKeys[0] });
    };
    handleReset = (clearFilters) => {
        clearFilters();
        this.setState({ searchText: '' });
    }

    // 添加用户的相关操作
    addModal = () => {
        this.setState({
            addModalVisible: true
        })
    }
    // 取消添加
    addCancel = () => {
        const form = this.addForm;
        form.resetFields();
        this.setState({
            addModalVisible: false
        })
    };
    // 添加
    addOk = () => {
        const form = this.addForm;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            // 添加用户
            fetchRequest.fetchR('users', 'post', values)
                .then(res => {
                    if (res.code === '200') {
                        message.success(res.message);
                        this.getUsersList();
                        this.setState({
                            addModalVisible: false
                        });
                    } else {
                        message.error(res.message);
                        this.setState({
                            addModalVisible: false
                        });
                    }
                }).catch(err => {
                    message.error('添加失败!');
                    this.setState({
                        addModalVisible: false
                    });
                })
            // 添加用户账单
            const body = {
                username: values.username,
                settlementDay: ''
            }
            fetchRequest.fetchR('settlement', 'post', body)
                .then(res => {

                }).catch(err => {
                    console.log(err)
                })
            form.resetFields();
        });
    };
    // 接受新建表单数据（添加）
    saveAddFormRef = (form) => {
        this.addForm = form;
    };

    // 用户查看
    lookClick = (username) => {
        this.props.history.push(`/app/userOrders/${username}`);
    }

    // 管理员订单查看
    lookAdminOrders = (name) => {
        this.props.history.push(`/app/managerOrders/${name}`);
    }

    render() {
        const { dataSource, visible, formData, addModalVisible } = this.state;
        const columns = [
            { title: '用户名', dataIndex: 'username', ...this.getColumnSearchProps('username'), },
            {
                title: '密码', dataIndex: 'password', render: (value) => {
                    return <Input value={value} disabled type='password'
                        style={{ textAlign: 'center', height: '28px', border: '0px', outline: 'none', cursor: 'pointer', background: 'transparent' }} />
                }
            },
            {
                title: '操作',
                dataIndex: 'opera',
                render: (text, record) =>
                    <div className='opera'>
                        <a onClick={() => this.lookClick(record.username)}>
                            <Icon type="file-text" /> 查看
                        </a>&nbsp;&nbsp;&nbsp;
                        <a onClick={() => this.editClick(record)}>
                            <Icon type="edit" /> 编辑
                        </a>&nbsp;&nbsp;&nbsp;
                        <a>
                            <Popconfirm title="确定要删除吗?" onConfirm={() => this.deleteClick(record)} okText='确定' cancelText='取消'>
                                <Icon type="minus-square-o" /> 删除 </Popconfirm>
                        </a>
                    </div>
            }
        ];
        return (
            <div>
                <BreadcrumbCustom paths={['首页']} />
                <div className='mindex'>
                    <Row>
                        <Col md={24}>
                            <Card>
                                <Button type='primary' onClick={this.addModal} >添加用户</Button>
                                <div style={{ float:'right' }}>
                                    <Button onClick={() => this.lookAdminOrders('admin')} >admin账户</Button>&nbsp;
                                    <Button onClick={() => this.lookAdminOrders('admin_1')} >admin_1账户</Button>
                                </div>
                                <Table
                                    rowKey="id"
                                    columns={columns}
                                    dataSource={dataSource}
                                />
                            </Card>
                        </Col>
                    </Row>
                </div>
                {/* 用户修改 */}
                <UserModal
                    ref={this.saveFormRef}
                    visible={visible}
                    formData={formData}
                    onCancel={this.handleCancel}
                    onCreate={this.handleUpdate} />
                {/* 用户添加 */}
                <AddModal
                    ref={this.saveAddFormRef}
                    addModalVisible={addModalVisible}
                    addCancel={this.addCancel}
                    dataSource={dataSource}
                    addOk={this.addOk} />
            </div>
        )
    }
}
